﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace CardFormatter
{
    public partial class MainForm : Form
    {
        public int GetRandom(int[] array)
        {
            Random rnd = new Random();
            int n = rnd.Next(array.Length - 1);
            return array[n];
        }
        public string ParentName;
        public int width;
        public int height;
        public Point StartPoint = new Point(0, 0);
        public Point EndPoint = new Point(0, 0);
        public bool beginDrag = false;
        public Graphics rectagle;
        public int Xmin;
        public int Xmax;
        public int Ymin;
        public int Ymax;
        public static BasicSettings basicSettings = new BasicSettings();
        private List<List<Button>> buttons;// button control array
        public List<Button> Points;//all points
        public List<Label> AxisLabels;//axis
        private delegate void ReadXML(string args);
        private delegate void SaveXML(string args);
        private delegate void ClearAndRedraw();
        public MainForm()
        {
            InitializeComponent();
            int[] Defaultsettings = new int[2];
            Defaultsettings[0] = 10;
            Defaultsettings[1] = 10;
            basicSettings.Settings = Defaultsettings;
            rectagle = this.CreateGraphics();
            Points = new List<Button>();
            AxisLabels = new List<Label>();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void OKEvent_Main()
        {
            Redraw();
        }
        public void Redraw()
        {
            ClearAndRedraw car = new ClearAndRedraw(RedrawThread);
            car.BeginInvoke(null, null);
        }
        public void RedrawThread()
        {
            ClearScreen();
            height = basicSettings.Settings[1];
            width = basicSettings.Settings[0];
            int[,] blkMap = CreateBlankMap(width,height);
            AbstractMapping abm = new AbstractMapping();
            abm.SetWidth(width);
            abm.SetHeight(height);
            abm.InitMap();
            abm.SetMap(blkMap);
            DrawAbstractMap(abm.GetMap());
        }
        private List<List<Button>> GetCapturedButtons(Point StartPoint,Point EndPoint)
        {
            List<List<Button>> capturedButtons = new List<List<Button>>();
            int minX = Math.Min(StartPoint.X, EndPoint.X);
            int minY = Math.Min(StartPoint.Y, EndPoint.Y);
            int maxX = Math.Max(StartPoint.X, EndPoint.X);
            int maxY = Math.Max(StartPoint.Y, EndPoint.Y);
            Point Start = new Point(0, 0);
            Point End = new Point(0, 0);
            List<int> XCoord = new List<int>();
            List<int> YCoord = new List<int>(); 
            foreach(Control ctrl in this.Controls)
            {
                if(ctrl.GetType().Name == "Button")
                {
                    Button btn = ctrl as Button;
                    if(btn.Location.X<maxX && btn.Location.X>minX)
                    {
                        char[] splitchar = new char[2];
                        splitchar[0] = 'X';
                        splitchar[1] = 'Y';
                        string btnX = btn.Name.Split(splitchar)[1];
                        XCoord.Add(int.Parse(btnX));
                        
                    }
                    if(btn.Location.Y < maxY && btn.Location.Y > minY)
                    {
                        char[] splitchar = new char[2];
                        splitchar[0] = 'X';
                        splitchar[1] = 'Y';
                        string btnY = btn.Name.Split(splitchar)[2];
                        YCoord.Add(int.Parse(btnY));
                    }                   
                }
            }
            if (XCoord.Count > 0 && YCoord.Count > 0)
            {
                Xmin = XCoord.Min();
                Xmax = XCoord.Max();
                Ymin = YCoord.Min();
                Ymax = YCoord.Max();
                for (int i = Ymin; i <= Ymax; i++)
                {
                    List<Button> btnList = new List<Button>();
                    for (int v = Xmin; v <= Xmax; v++)
                    {
                        btnList.Add(this.Controls["BtnX" + v.ToString() + "Y" + i.ToString()] as Button);
                    }
                    capturedButtons.Add(btnList);
                }
            }
            return capturedButtons;         
        }
        private int[,] CreateBlankMap(int width, int height)
        {
            int[,] BlkMap = new int[width, height];
            for (int i = 0; i < height; i++)
            {
                for (int v = 0; v < width; v++)
                {
                    BlkMap[v, i] = 4;
                }
            }
            return BlkMap;
        }
        private int[,] CreateSequencedMap(int width, int height)
        {
            int[] TypeArray = new int[5];
            for (int b = 0; b < 5; b++)
            {
                TypeArray[b] = b;
            }
            int[,] SeqMap = new int[width, height];
            for (int i = 0; i < height; i++)
            {
                for (int v = 0; v < width; v++)
                {
                    int seq = (v + i) % 5;
                    SeqMap[v, i] = TypeArray[seq];
                }
            }
            return SeqMap;
        }
        private void DrawAbstractMap(BlankDot[,] AbstractMap)
        {
            int width = 0;
            int height = 0;
            int[] initPos = new int[2];
            initPos[0] = 50;
            initPos[1] = 60;
            int[] deltaPos = new int[2];
            deltaPos[0] = 62;
            deltaPos[1] = 29;
            int[] btnSize = new int[2];
            btnSize[0] = 56;
            btnSize[1] = 23;
            width = AbstractMap.GetLength(0);
            height = AbstractMap.GetLength(1);
            DrawAxis(width, height);
            for (int i = 0; i < height; i++)
            {
                for (int v = 0; v < width; v++)
                {
                    int[] curPos = new int[2];
                    curPos[0] = initPos[0] + deltaPos[0] * v;
                    curPos[1] = initPos[1] + deltaPos[1] * i;
                    Button btn = new Button()
                    {
                        Name = "BtnX" + v.ToString() + "Y" + i.ToString()
                    };
                    int category = AbstractMap[v, i].DotCategory;
                    string btnTxt = "";
                    string btnType = "";
                    if (category == 0)
                    {
                        btnTxt = "AN";
                        btnType = "0";
                    }
                    else if (category == 1)
                    {
                        btnTxt = "MinT";
                        btnType = "1";
                    }
                    else if (category == 2)
                    {
                        btnTxt = "ID";
                        btnType = "2";
                    }
                    else if (category == 3)
                    {
                        btnTxt = "MajT";
                        btnType = "3";
                    }
                    else
                    {
                        btnTxt = " ";
                        btnType = "4";
                    }
                    string defaultValue = "BLK";
                    List<string> btnTag = new List<string>();
                    btnTag.Add(btnType);
                    btnTag.Add(defaultValue);
                    btn.Text = btnTxt;
                    btn.Tag = btnTag;
                    btn.Size = new Size(btnSize[0], btnSize[1]);
                    btn.Location = new Point(curPos[0], curPos[1]);
                    
                    ContextMenuStrip cms = new ContextMenuStrip();
                    ContextMenuItemInit(cms);
                    cms.Opening += ContextMenuOpening;
                    btn.ContextMenuStrip = cms;
                    Points.Add(btn);
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(delegate
                        {
                            this.Controls.Add(btn);
                        }));
                    }
                    else
                    {
                        this.Controls.Add(btn);
                    }

                }
            }
        }
        private void FillMenuItemInit(ContextMenuStrip cms)
        {
            ToolStripMenuItem blk = new ToolStripMenuItem()
            {
                Text = " "
            };
            blk.Click += SetBlockBlank;
            cms.Items.Add(blk);
            ToolStripMenuItem ans = new ToolStripMenuItem()
            {
                Text = "答案"
            };
            ToolStripMenuItem TopDown = new ToolStripMenuItem()
            {
                Text = "↓"
            };
            TopDown.Click += FillMenuItemClick;
            ToolStripMenuItem LeftRight = new ToolStripMenuItem()
            {
                Text = "→"
            };
            LeftRight.Click += FillMenuItemClick;
            ToolStripMenuItem DownTop = new ToolStripMenuItem()
            {
                Text = "↑"
            };
            DownTop.Click += FillMenuItemClick;
            ToolStripMenuItem RightLeft = new ToolStripMenuItem()
            {
                Text = "←"
            };
            RightLeft.Click += FillMenuItemClick;
            ans.DropDownItems.Add(TopDown);
            ans.DropDownItems.Add(LeftRight);
            ans.DropDownItems.Add(DownTop);
            ans.DropDownItems.Add(RightLeft);
            cms.Items.Add(ans);

            ToolStripMenuItem id = new ToolStripMenuItem()
            {
                Text = "身份识别"
            };
            ToolStripMenuItem TopDown1= new ToolStripMenuItem()
            {
                Text = "↓"
            };
            TopDown1.Click += FillMenuItemClick;
            ToolStripMenuItem LeftRight1 = new ToolStripMenuItem()
            {
                Text = "→"
            };
            LeftRight1.Click += FillMenuItemClick;
            ToolStripMenuItem DownTop1 = new ToolStripMenuItem()
            {
                Text = "↑"
            };
            DownTop1.Click += FillMenuItemClick;
            ToolStripMenuItem RightLeft1 = new ToolStripMenuItem()
            {
                Text = "←"
            };
            RightLeft1.Click += FillMenuItemClick;
            id.DropDownItems.Add(TopDown1);
            id.DropDownItems.Add(LeftRight1);
            id.DropDownItems.Add(DownTop1);
            id.DropDownItems.Add(RightLeft1);
            cms.Items.Add(id);


        }
        private void SetBlockBlank(object sender, EventArgs e)
        {
            ToolStripMenuItem tsi = sender as ToolStripMenuItem;
            string Type = tsi.Text;
            if (Type == "BLK")
            {
                foreach (List<Button> lbtn in buttons)
                {
                    foreach (Button btn in lbtn)
                    {
                        btn.Tag = SetButtonTag("4", "BLK");
                        btn.Text = " ";
                    }
                }
            }
        }
        private void FillMenuItemClick(object sender,EventArgs e)
        {
            ToolStripMenuItem tsi = sender as ToolStripMenuItem;
            string orientation = tsi.Text;
            string answerString = "ABCDEFGH";
            
            if(orientation == "→")
            {
                if (tsi.OwnerItem.Text == "答案")
                {
                    for (int i = Ymin; i <= Ymax; i++)
                    {
                        int y = i - Ymin;
                        for (int v = Xmin; v <= Xmax; v++)
                        {
                            int x = v - Xmin;
                            string tgt = answerString[x%8].ToString();
                            buttons[y][x].Text = tgt;
                            buttons[y][x].Tag = SetButtonTag("0", tgt);
                        }
                    }
                }
                else
                {
                    answerString = "0123456789";
                    for (int i = Ymin; i <= Ymax; i++)
                    {
                        int y = i - Ymin;
                        for (int v = Xmin; v <= Xmax; v++)
                        {
                            int x = v - Xmin;
                            string tgt = answerString[x%10].ToString();
                            buttons[y][x].Text = tgt;
                            buttons[y][x].Tag = SetButtonTag("2", tgt);
                        }
                    }
                }
            }
            else if (orientation == "←")
            {
                if (tsi.OwnerItem.Text == "答案")
                {
                    for (int i = Ymin; i <= Ymax; i++)
                    {
                        int y = i - Ymin;
                        for (int v = Xmax; v >= Xmin; v--)
                        {
                            int x = v - Xmin;
                            int arrayPos = Xmax - v;
                            string tgt = answerString[arrayPos%8].ToString();
                            buttons[y][x].Text = tgt;
                            buttons[y][x].Tag = SetButtonTag("0", tgt);
                        }
                    }
                }
                else
                {
                    answerString = "0123456789";
                    for (int i = Ymin; i <= Ymax; i++)
                    {
                        int y = i - Ymin;
                        for (int v = Xmax; v >= Xmin; v--)
                        {
                            int x = v - Xmin;
                            int arrayPos = Xmax - v;
                            string tgt = answerString[arrayPos%10].ToString();
                            buttons[y][x].Text = tgt;
                            buttons[y][x].Tag = SetButtonTag("2", tgt);
                        }
                    }
                }
            }
            else if (orientation == "↑")
            {
                if (tsi.OwnerItem.Text == "答案")
                {
                    for (int i = Xmin; i <= Xmax; i++)
                    {
                        int y = i - Xmin;
                        for (int v = Ymax; v >= Ymin; v--)
                        {
                            int x = v - Ymin;
                            int arrayPos = Xmax - v;
                            string tgt = answerString[arrayPos%8].ToString();
                            buttons[x][y].Text = tgt;
                            buttons[x][y].Tag = SetButtonTag("0", tgt);
                        }
                    }
                }
                else
                {
                    answerString = "0123456789";
                    for (int i = Xmin; i <= Xmax; i++)
                    {
                        int y = i - Xmin;
                        for (int v = Ymax; v >= Ymin; v--)
                        {
                            int x = v - Ymin;
                            int arrayPos = Xmax - v;
                            string tgt = answerString[arrayPos%10].ToString();
                            buttons[x][y].Text = tgt;
                            buttons[x][y].Tag = SetButtonTag("2", tgt);
                        }
                    }
                }
            }
            else if (orientation == "↓")
            {
                if (tsi.OwnerItem.Text == "答案")
                {
                    for (int i = Xmin; i <= Xmax; i++)
                    {
                        int y = i - Xmin;
                        for (int v = Ymin; v <= Ymax; v++)
                        {
                            int x = v - Ymin;
                            string tgt = answerString[x%8].ToString();
                            buttons[x][y].Text = tgt;
                            buttons[x][y].Tag = SetButtonTag("0", tgt);
                        }
                    }
                }
                else
                {
                    answerString = "0123456789";
                    for (int i = Xmin; i <= Xmax; i++)
                    {
                        int y = i - Xmin;
                        for (int v = Ymin; v <= Ymax; v++)
                        {
                            int x = v - Ymin;
                            string tgt = answerString[x%10].ToString();
                            buttons[x][y].Text = tgt;
                            buttons[x][y].Tag = SetButtonTag("2", tgt);
                        }
                    }
                }
            }
        }
        private List<string> SetButtonTag(string Type,string Value)
        {
            List<string> tag = new List<string>();
            tag.Add(Type);
            tag.Add(Value);
            return tag;
        }
        private void ContextMenuItemInit(ContextMenuStrip cms)
        {
            ToolStripMenuItem ans = new ToolStripMenuItem()
            {
                Text = "答案"
            };
            ToolStripMenuItem ANS0 = new ToolStripMenuItem("A");
            ANS0.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS0);
            ToolStripMenuItem ANS1 = new ToolStripMenuItem("B");
            ANS1.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS1);
            ToolStripMenuItem ANS2 = new ToolStripMenuItem("C");
            ANS2.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS2);
            ToolStripMenuItem ANS3 = new ToolStripMenuItem("D");
            ANS3.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS3);
            ToolStripMenuItem ANS4 = new ToolStripMenuItem("E");
            ANS4.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS4);
            ToolStripMenuItem ANS5 = new ToolStripMenuItem("F");
            ANS5.Click += new EventHandler(ContextMenuStripClickEvent);
            ans.DropDownItems.Add(ANS5);
            ToolStripMenuItem MinT = new ToolStripMenuItem()
            {
                Text = "次级分类"
            };
            ToolStripMenuItem mT0 = new ToolStripMenuItem("X");
            mT0.Click += new EventHandler(ContextMenuStripClickEvent);
            MinT.DropDownItems.Add(mT0);
            ToolStripMenuItem mT1 = new ToolStripMenuItem("Y");
            mT1.Click += new EventHandler(ContextMenuStripClickEvent);
            MinT.DropDownItems.Add(mT1);
            ToolStripMenuItem mT2 = new ToolStripMenuItem("Z");
            mT2.Click += new EventHandler(ContextMenuStripClickEvent);
            MinT.DropDownItems.Add(mT2);
            ToolStripMenuItem MajT = new ToolStripMenuItem()
            {
                Text = "主分类"
            };
            ToolStripMenuItem MT0 = new ToolStripMenuItem("A");
            MT0.Click += new EventHandler(ContextMenuStripClickEvent);
            MajT.DropDownItems.Add(MT0);
            ToolStripMenuItem MT1 = new ToolStripMenuItem("B");
            MT1.Click += new EventHandler(ContextMenuStripClickEvent);
            MajT.DropDownItems.Add(MT1);
            ToolStripMenuItem ID = new ToolStripMenuItem()
            {
                Text = "身份识别"
            };
            ToolStripMenuItem ID0 = new ToolStripMenuItem("0");
            ID0.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID0);
            ToolStripMenuItem ID1 = new ToolStripMenuItem("1");
            ID1.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID1);
            ToolStripMenuItem ID2 = new ToolStripMenuItem("2");
            ID2.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID2);
            ToolStripMenuItem ID3 = new ToolStripMenuItem("3");
            ID3.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID3);
            ToolStripMenuItem ID4 = new ToolStripMenuItem("4");
            ID4.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID4);
            ToolStripMenuItem ID5 = new ToolStripMenuItem("5");
            ID5.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID5);
            ToolStripMenuItem ID6 = new ToolStripMenuItem("6");
            ID6.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID6);
            ToolStripMenuItem ID7 = new ToolStripMenuItem("7");
            ID7.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID7);
            ToolStripMenuItem ID8 = new ToolStripMenuItem("8");
            ID8.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID8);
            ToolStripMenuItem ID9 = new ToolStripMenuItem("9");
            ID9.Click += new EventHandler(ContextMenuStripClickEvent);
            ID.DropDownItems.Add(ID9);
            ToolStripMenuItem BLK = new ToolStripMenuItem()
            {
                Text = "空白"
            };
            BLK.Click += SetBlankEvent;
            cms.Items.Add(BLK);
            cms.Items.Add(ans);
            cms.Items.Add(ID);
            cms.Items.Add(MinT);
            cms.Items.Add(MajT);
        }
        private void SetBlankEvent(object sender, EventArgs e)
        {
            ToolStripItem tsi = sender as ToolStripItem;
            string name = tsi.Text;
            Button parent = this.Controls[ParentName] as Button;
            List<string> TAGS = new List<string>();
            TAGS.Add("4");
            TAGS.Add("BLK");
            parent.Tag = TAGS;
            parent.Text = " ";
        }

        private void ContextMenuOpening(object sender, CancelEventArgs e)
        {
            ContextMenuStrip cms = sender as ContextMenuStrip;
            Control c = cms.SourceControl;
            ParentName = c.Name;
            //MessageBox.Show(name);
            cms.TopLevel = true;
        }
        private void ContextMenuStripClickEvent(object sender, EventArgs e)
        {
            try
            {
                ToolStripItem dpm = sender as ToolStripItem;
                string name = dpm.Text;
                ContextMenuStrip cms = dpm.OwnerItem.Owner as ContextMenuStrip;
                Button parent = this.Controls[ParentName] as Button;
                if (parent.GetType().Name == "Button")
                {
                    string classification = dpm.OwnerItem.Text;
                    List<string> Class = new List<string>();
                    if (classification == "答案")
                    {
                        Class.Add("0");
                    } else if (classification == "次级分类")
                    {
                        Class.Add("1");
                    } else if (classification == "身份识别")
                    {
                        Class.Add("2");
                    } else if (classification == "主分类")
                    {
                        Class.Add("3");
                    }
                    else
                    {
                        Class.Add("4");
                    }
                    Class.Add(name);
                    parent.Tag = Class;
                    parent.Text = name;
                }

            }
            catch
            {
                Exception excption = new Exception();
                MessageBox.Show(excption.ToString());
            }
        }
        private void ClearScreen()
        {
            /*for (int i = 0; i < height; i++)
            {
                Label lbl = this.Controls["LabelY" + i.ToString()] as Label;
                lbl.Dispose();
                for (int v = 0; v < width; v++)
                {
                    Button btn = this.Controls["BtnX" + v.ToString() + "Y" + i.ToString()] as Button;                   
                    btn.Dispose();
                }
            }*/
            foreach (Button btn in Points)
            {
                btn.Dispose();
            }
            foreach (Label lbl in AxisLabels)
            {
                this.Controls.Remove(lbl);
                lbl.Dispose();
            }
        }
        private void XMLRead(string args)
        {
            ReadXML read = new ReadXML(XMLReadThread);
            read.BeginInvoke(args, null, null);
        }
        private void XMLReadThread(string path)
        {
            XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load(path);
                XmlNode node = doc.SelectSingleNode("Card");
                if(node != null)
                {
                    XmlNode settings = node.SelectSingleNode("Setup");
                    if(settings != null)
                    {
                        ClearScreen();
                        XmlNodeList xnl = settings.ChildNodes;
                        XmlElement xWidth = xnl[0] as XmlElement;
                        XmlElement xHeight = xnl[1] as XmlElement;
                        width = int.Parse(xWidth.InnerText);
                        height = int.Parse(xHeight.InnerText);
                        XmlNode Map = node.SelectSingleNode("Map");
                        if (Map != null)
                        {
                            XmlNodeList pointList = Map.ChildNodes;
                            int[,] BlkMap = CreateBlankMap(width, height);
                            AbstractMapping abstractMap = new AbstractMapping();
                            abstractMap.SetHeight(height);
                            abstractMap.SetWidth(width);
                            abstractMap.InitMap();
                            abstractMap.SetMap(BlkMap);
                            DrawAbstractMap(abstractMap.GetMap());
                            if (pointList != null)
                            {
                                for (int i = 0; i < height; i++)
                                {
                                    for (int v = 0; v < width; v++)
                                    {
                                        XmlNode point = pointList[i*width+v];
                                        if(point != null)
                                        {
                                            XmlNodeList Args = point.ChildNodes;
                                            List<string> iList = new List<string>();
                                            string type = Args.Item(0).InnerText;
                                            string value = Args.Item(1).InnerText;
                                            iList.Add(type);
                                            iList.Add(value);
                                            Button btn = this.Controls["BtnX" + v.ToString() + "Y" + i.ToString()] as Button;
                                            btn.Tag = iList;
                                            if (value == "BLK")
                                            {
                                                btn.Text = " ";
                                            }
                                            else
                                            {
                                                btn.Text = value;
                                            }
                                            
                                            
                                        }                                  
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        private void XMLSave(string path)
        {
            SaveXML save = new SaveXML(XMLSaveThread);
            save.BeginInvoke(path, null, null);
        }
        
        private void XMLSaveThread(string path)
        {
            XmlDocument doc = new XmlDocument();
            XmlNode node = doc.CreateXmlDeclaration("1.0", "utf-8", "");
            XmlNode root = doc.CreateElement("Card");
            doc.AppendChild(root);
            XmlNode settings = doc.CreateElement("Setup");
            CreateNode(doc, settings, "width", width.ToString());
            CreateNode(doc, settings, "height", height.ToString());
            root.AppendChild(settings);
            XmlNode Map = doc.CreateElement("Map");
            for (int i = 0; i < height; i++)
            {
                for (int v = 0; v < width; v++)
                {
                    List<string> iList = new List<string>();
                    iList = this.Controls["BtnX" + v.ToString() + "Y" + i.ToString()].Tag as List<string>;
                    string type = iList[0];
                    string value = iList[1];
                    XmlNode Node = doc.CreateElement("PositionX" + v.ToString() + "Y" + i.ToString());
                    Map.AppendChild(Node);
                    CreateNode(doc, Node, "type", type);
                    CreateNode(doc, Node, "value", value);
                }
            }
            root.AppendChild(Map);
            try
            {
                doc.Save(path);
                MessageBox.Show("Saved "+path);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
            
        }
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

        private void 基本设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BasicSettingsForm Bsf = new BasicSettingsForm();
            Bsf.Show();
            Bsf.OkEvent += new BasicSettingsForm.OkEventDelegate(OKEvent_Main);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            width = 10;
            height = 10;
            int[,] BlkMap = CreateBlankMap(width, height);

            int[,] RndMap = CreateSequencedMap(width, height);
            AbstractMapping abstractMap = new AbstractMapping();
            abstractMap.SetHeight(height);
            abstractMap.SetWidth(width);
            abstractMap.InitMap();
            abstractMap.SetMap(BlkMap);
            DrawAbstractMap(abstractMap.GetMap());
        }

        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog() {
                Title = "保存文件",
                Filter= "XML Files(*.xml)|*.xml"
            };
            if(sfd.ShowDialog() == DialogResult.OK)
            {
                string filename = sfd.FileName;
                XMLSave(filename);
                //MessageBox.Show("Saved :" + filename);
            }

        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog() {
                Title = "请选择卡格式XML文件",
                Filter="XML Files(*.xml)|*.xml"
            };
            if(ofd.ShowDialog()== DialogResult.OK)
            {
                string filename = ofd.FileName;
                XMLRead(filename);
            }
        }

        private void MainForm_MouseDown(object sender, MouseEventArgs e)
        {
            beginDrag = true;
            StartPoint = new Point(e.X, e.Y);
        }
        private void DrawAxis(int X,int Y)
        {
            int[] initPos = new int[2];
            initPos[0] = 50;
            initPos[1] = 60;
            int[] deltaPos = new int[2];
            deltaPos[0] = 62;
            deltaPos[1] = 29;
            Point Ystartpos = new Point(10,65);
            for (int i = 0; i < Y; i++)
            {
                Point curPosition = new Point(Ystartpos.X, Ystartpos.Y + (deltaPos[1] * i));
                Label curLabel = new Label();
                curLabel.Name = "LabelY" + i.ToString();
                curLabel.Location = curPosition;
                curLabel.Text = i.ToString();
                curLabel.Width = 20;
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Controls.Add(curLabel);
                    }));
                }
                else
                {
                    this.Controls.Add(curLabel);
                }
                AxisLabels.Add(curLabel);
            }
            Point XstartPos = new Point(55, 25);
            for (int i = 0; i < X; i++)
            {
                Point curPosition = new Point(XstartPos.X + (deltaPos[0] * i), XstartPos.Y);
                Label curLabel = new Label();
                curLabel.Name = "LabelX" + i.ToString();
                curLabel.Location = curPosition;
                curLabel.Text = i.ToString();
                curLabel.Width = 20;
                AxisLabels.Add(curLabel);
                if (this.InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.Controls.Add(curLabel);
                    }));
                }
                else
                {
                    this.Controls.Add(curLabel);
                }
            }

        }

        private void MainForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (beginDrag)
            {
                rectagle.Clear(this.BackColor);
                EndPoint = new Point(e.X, e.Y);
                int minX = Math.Min(StartPoint.X, EndPoint.X);
                int minY = Math.Min(StartPoint.Y, EndPoint.Y);
                int maxX = Math.Max(StartPoint.X, EndPoint.X);
                int maxY = Math.Max(StartPoint.Y, EndPoint.Y);
                rectagle.DrawRectangle(new Pen(Color.Black), minX, minY, maxX - minX, maxY - minY);                
            }
        }

        private void MainForm_MouseUp(object sender, MouseEventArgs e)
        {
            beginDrag = false;
            buttons = GetCapturedButtons(StartPoint, EndPoint);
            ContextMenuStrip cms = new ContextMenuStrip();
            FillMenuItemInit(cms);
            cms.Show(this, EndPoint);
        }
        public class BasicSettings
        {
            private int Width;
            private int Height;
            private int[] setups = new int[2];
            public void SetSettings(int width, int height)
            {
                Width = width;
                Height = height;
            }
            public int[] Settings
            {
                get
                {
                    setups[0] = Width;
                    setups[1] = Height;
                    return setups;
                }
                set
                {
                    Width = value[0];
                    Height = value[1];
                }
            }
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            rectagle = this.CreateGraphics();
        }

        private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BasicSettingsForm bsf = new BasicSettingsForm();
            bsf.Show();
            bsf.OkEvent += new BasicSettingsForm.OkEventDelegate(OKEvent_Main);
        }
    }

}
